package com.sy.msgview

import android.app.Application
import android.net.Uri
import android.widget.Toast
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import androidx.room.Room
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

class QQViewModel(private val application: Application) : AndroidViewModel(application) {
	private val database: QQDatabase by lazy {
		Room.databaseBuilder(
			application, QQDatabase::class.java, Utils.getDatabase(application, override = false)
		).build()
	}
	private val qqListDao by lazy { database.qqListDao() }
	private val qqMsgDao by lazy { database.msgItemDao() }
	private var _offset = 0
	var msgList = MutableStateFlow(listOf<QQMsgItem>())


	fun getQQList(): Flow<MutableList<QQItem>> {
		return qqListDao.getAllQQ().map { item ->
			item.find { it.qq == 2509337306 }?.let {
				item.remove(it)
				item.add(0, it)
			}
			item
		}
	}

	suspend fun getQQMsg(qq: Long, count: Int = 15, next: Boolean = true) {
		if (next) _offset += count
		else {
			_offset = 0
			msgList.value = listOf()
		}
		qqMsgDao.getMsgItem(qq, count, _offset).collect {
			it.addAll(0, msgList.value)
			msgList.value = it
		}
	}


	fun uploadDatabase(uri: Uri) {
		database.close()
		//获得ContentResolver，用于访问其它应用数据
		val resolver = application.contentResolver
		//新文件的路径 程序数据库目录路径
		val databasePath = application.getDatabasePath("backup.db")
		if (databasePath.exists()) databasePath.delete()
		//创建文件
		val inputStream = resolver.openInputStream(uri)
		val outputStream = FileOutputStream(databasePath)
		inputStream?.let {
			val buffer = ByteArray(1024)
			var length: Int
			while (inputStream.read(buffer).also { length = it } > 0) {
				outputStream.write(buffer, 0, length)
			}
			outputStream.flush()
			inputStream.close()
			outputStream.close()
		}
	}
}